const db = require('../models')

class UsersRepository {
  /**
   * 添加新用户
   * @param {Object} userData - 用户数据
   * @returns {Promise<Object>} - 返回新用户信息
   */
  async addNewUser(userData) {
    try {
      const newUser = await db.Users.create(userData);
      return newUser;
    } catch (error) {
      throw error;
    }
  }

  async delUserById(id) {
    const user = await db.Users.findByPk(id);
    return user ? (await user.destroy(), true) : false;
  }

  async updateUserById(id, userData) {
    const user = await db.Users.findByPk(id);
    if (!user) return false;
    // 更新用户数据
    const [affectedRows] = await db.Users.update(userData, {
      where: { id }, // 添加 where 条件
    });
    return affectedRows > 0; // 返回是否更新成功
  }

  async getAllUsers() {
    return await db.Users.findAll();
  }
  /* 获取用户详细信息 用户端 */
  async getUserById(id) {
    return await db.Users.findByPk(id, {
      attributes: [
        "nickname",
        "email",
        "tel",
        "xuexiao",
        "xueyuan",
        "zhuanye",
        "xuehao",
        "money"
      ],
    });
  }

  /**
   * 根据账号查询用户
   * @param {string} account - 用户账号
   * @returns {Promise<Object|null>} - 返回用户信息或 null
   */
  async getUserByAccount(account) {
    try {
      const user = await db.Users.findOne({
        where: { account }, // 根据 account 查询
        attributes: [
          "id",
          "nickname",
          "account",
          "avatar",
          "password",
          "state",
          "money",
          "createdAt",
          "banreason",
          "email",
          "tel",
          "xuexiao",
          "xueyuan",
          "xuehao",
          "zhuanye",
        ], // 返回需要的字段
      });
      return user;
    } catch (error) {
      throw error;
    }
  }
  /* 上传头像 */
  async uploadAvatar(id, avatarUrl) {
    try {
      const user = await db.Users.findByPk(id);
      if (!user) return false;
      const [affectedRows] = await db.Users.update(
        { avatar: avatarUrl },
        { where: { id } }
      );
      return affectedRows > 0;
    } catch (e) {
      console.log("更新头像失败: ");
      console.log(e);
    }
  }
  /* 封禁用户 */
  async banUser(id, banreason) {
    try {
      const user = await db.Users.findByPk(id);
      if (!user) return false;
      const [affectedRows] = await db.Users.update(
        { banreason, state: 0 },
        { where: { id } }
      );
      return affectedRows > 0;
    } catch (e) {
      console.log("封禁用户失败: ");
      console.log(e);
    }
  }
  /* 根据昵称对用户模糊查询 */
  async getUserByAccMH(account) {
    try {
      // 使用 Sequelize 的 Op.like 操作符进行模糊查询
      const users = await db.Users.findAll({
        where: {
          account: {
            [db.Sequelize.Op.like]: `%${account}%`, // 模糊匹配昵称
          },
        },
        attributes: ["id", "nickname", "account", "avatar"], // 返回需要的字段
      });
      return users; // 返回查询结果
    } catch (error) {
      console.log(`模糊查询出错啦!${e}`);
    }
  }
  /* 解封用户 */
  async releaseUser(id) {
    try {
      const user = await db.Users.findByPk(id);
      if (!user) return false;
      const [affectedRows] = await db.Users.update(
        { banreason: "nothing", state: 1 },
        { where: { id } }
      );
      return affectedRows > 0;
    } catch (e) {
      console.log("解封用户失败: ");
      console.log(e);
    }
  }
  /* 管理员根据ID获取用户全部信息 */
  async getUserByIdPlus(id) {
    return await db.Users.findByPk(id);
  }

  /* 根据 ID 更新用户详细信息 */
  async updateUserDetailsById(id, newData) {
    try {
      // 确保只更新允许的字段
      const allowedFields = [
        "nickname",
        "email",
        "tel",
        "xuexiao",
        "xueyuan",
        "zhuanye",
        "xuehao",
        "updatedAt",
      ];
      const updateData = {};
      allowedFields.forEach((field) => {
        if (newData[field] !== undefined) {
          updateData[field] = newData[field];
        }
      });
      if (Object.keys(updateData).length === 0) return false;
      const [affectedRows] = await db.Users.update(updateData, {
        where: { id },
      });
      return affectedRows > 0;
    } catch (error) {
      console.log("更新用户详细信息失败:", error);
    }
  }
  /* 根据ID查询用户密码 */
  async getUserPwdById(id) {
    const user = await db.Users.findByPk(id);
    if (!user) return false;
    const pwd = await db.Users.findOne({
      where: { id },
      attributes: ["password"],
    });
    return pwd;
  }
  /* 修改用户密码 */
  async resetPwdById(id, password) {
    const user = await db.Users.findByPk(id);
    if (!user) return false;
    const [affectedRows] = await db.Users.update(
      { password, updateAt: new Date().toLocaleDateString },
      { where: { id } }
    );
    return affectedRows;
  }
  /* 充值接口 = 根据 id 更新用户 money 字段 */
  async updateMoneyById(id, amount) {
    try {
      // 检查用户是否存在
      const user = await db.Users.findByPk(id);
      if (!user) 
        return false
      await user.increment('money', { by: amount })
      // 返回更新后的用户信息
      return true
    } catch (e) {
      console.log('充值接口-更新余额失败: ')
      console.log(e)
      return false
    }
  
  }
  /* 提现接口 */
  async tiXian(id, amount) {
    const user = await db.Users.findByPk(id);
    console.log('user: ')
    console.log(user)
    if (!user) return false;
    // 检查用户余额是否足够
    if (user.money < amount) 
      return false
    user.money -= amount;
    await user.save();
    return true;
  }
}
 
module.exports = new UsersRepository()